package org.ysu.service.impl;

import io.minio.errors.*;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ysu.core.YsuException;
import org.ysu.dto.CombinedFormData;
import org.ysu.service.FamilyService;
import org.ysu.service.InterviewService;
import org.ysu.service.PoorService;
import org.ysu.service.UpInterviewService;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class UpInterviewServiceImpl implements UpInterviewService {
    @Resource
    private FamilyService familyService;
    @Resource
    private InterviewService interviewService;
    @Resource
    private PoorService poorService;

    @Transactional
    public Boolean add(CombinedFormData formData) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean familySuccess= false;
        try {
            familySuccess = familyService.add(
                    formData.getFId(),
                    formData.getPName(),
                    formData.getPNumber(),
                    formData.getRId(),
                    formData.getVcId(),
                    formData.getProvince(),
                    formData.getCity(),
                    formData.getCounty(),
                    formData.getTownship(),
                    formData.getVillage()
            );
        } catch (Exception e) {
            throw new YsuException("家庭信息填报有误，请修改后重新提交");
        }

        boolean interviewSuccess= false;
        try {
            interviewSuccess = interviewService.add(
                    formData.getVcId(),
                    formData.getFId(),
                    formData.getTime(),
                    formData.getRiskType(),
                    formData.getRiskRemark(),
                    formData.getIncome(),
                    formData.getLiability(),
                    formData.getSuggestion(),
                    formData.getDetail(),
                    formData.getPhoto()
            );
        } catch (DataIntegrityViolationException e) {
            throw new  YsuException("走访信息填报有误，请修改后重新提交");
        }


        boolean poorSuccess= false;
        try {
            poorSuccess = poorService.add(formData.getPoorPeople());
        } catch (Exception e) {
            throw new YsuException("贫困人员信息填报有误，请修改后重新提交");
        }

        if (!familySuccess) {
            throw new YsuException("家庭信息填报有误，请修改后重新提交");
        }
        if (!interviewSuccess) {
            throw new YsuException("走访信息填报有误，请修改后重新提交");
        }
        if (!poorSuccess) {
            throw new YsuException("贫困人员信息填报有误，请修改后重新提交");
        }
        return true;
    }


}
